﻿using WorkflowCore.Interface;
using WorkflowCore.Service.Manger;
using WorkflowCore.Service.Persisted;

namespace Workflow_Core_API
{
    public static class WorkflowExtenssion
    {
        public static void UseWorkflow(this WebApplication app)
        {
            var host = app.Services.GetService<IWorkflowHost>();
            host.Start(); // 启动服务

            // 测试代码，可以删除
            // host.RegisterWorkflow<HelloWorldWorkflow>();

            var lifetime = app.Services.GetService<IHostApplicationLifetime>();
            // 应用程序启动时
            lifetime.ApplicationStarted.Register(() =>
            {
                var workflowService = app.Services.GetService<IWorkflowManger>();
                var db = app.Services.GetService<WorkflowCoreDbcontext>();
                var list = db.persistedWorkflowDefinition.Where(p => p.IsLastVersion).ToList();
                foreach (var definition in list)
                {
                    workflowService.AddDefinition(definition);
                }
            });

            // 应用程序结束时
            lifetime.ApplicationStopping.Register(() =>
            {
                host.Stop();
            });
        }
    }
}
